package com.practice.designMode.builder;

/**
 * 建造者模式 —— 链式调用 灵活处理构建过程 封装构建隐藏逻辑
 * 对User的构建进行建造者模式改造
 */
public class User {

    /**
     * User对象属性有特殊check规则
     * 为了保证合法性，创建之后应该是不允许修改的
     * 因此这里用final进行修饰
     */
    private final String name;
    private final int age;

    private User(Builder builder){
        this.name = builder.name;
        this.age = builder.age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static Builder builder(){
        return new Builder();
    }

    public static class Builder{

        private String name;
        private int age;

        public Builder name(String name){
            this.name = name;
            return this;
        }

        public Builder age(int age){
            this.age = age;
            return this;
        }

        public User build(){
            check();
            return new User(this);
        }

        private void check(){
            // 任意对于属性的判断逻辑
        }
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
